package com.corpdata.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpUtils {
	
	public static String getHttpClient(String url,String cid,String v,String p,String sn,String tn) {
		// 生成MD5签名
			String s = "";
			try {
				// 构造参数
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(url);
				ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
				list.add(new BasicNameValuePair("cid", cid));
				list.add(new BasicNameValuePair("v", v));
				list.add(new BasicNameValuePair("p",p));
				list.add(new BasicNameValuePair("sn",sn));
				list.add(new BasicNameValuePair("tn",tn));
				HttpEntity en = new UrlEncodedFormEntity(list, HTTP.UTF_8);
				post.setEntity(en);
				
				// 发送消息和处理结果
				HttpResponse response = client.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					System.out.println("执行成功！");
					s = EntityUtils.toString(response.getEntity());
					System.out.println(s);
				} else {
					System.out.println("执行失败！");
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return s;
		}
	
	
	public static String toHexString(byte[] bytes) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			buffer.append(String.format("%02X", bytes[i]));
		}
		return buffer.toString();
	}
	
	public static HashMap<String, String> jsonStr2Map(String jsonStr) {
		JSONObject jsonobj = JSON.parseObject(jsonStr);
		HashMap<String, String> map = new HashMap<String, String>(jsonobj
				.size());
		for (String fdName : jsonobj.keySet()) {
			map.put(fdName, jsonobj.getString(fdName));
		}
		return map;
	}
	
	public static String httpPost(String url, String params) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient httpclient = HttpClients.custom().build();
		StringEntity myEntity = new StringEntity(params,ContentType.APPLICATION_JSON);
		httpPost.setEntity(myEntity);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			HttpEntity rsEntity = response.getEntity();
			if (rsEntity != null) {
				InputStream instream = rsEntity.getContent();
				String str = streamToString(instream, "UTF-8");
				return str;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			response.close();
		}
		response.close();

		return "";
	}

	public static String httpPost(String url, HashMap<String, String> params)throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient httpclient = HttpClients.custom().build();
		List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
		for (String keyName : params.keySet()) {
			formParams.add(new BasicNameValuePair(keyName, (String) params.get(keyName)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,"UTF-8");
		httpPost.setEntity(entity);

		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			HttpEntity rsEntity = response.getEntity();
			if (rsEntity != null) {
				InputStream instream = rsEntity.getContent();
				String str = streamToString(instream, "UTF-8");
				return str;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			response.close();
		}
		response.close();
		return "";
	}
	
	public static String streamToString(InputStream is, String charset)
			throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,charset));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null)
				sb.append(line + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static String httpGet(String url, String charset) throws Exception {
		if (isBlank(charset)) {
			charset = "UTF-8";
		}
		HttpGet httpget = new HttpGet(url);
		CloseableHttpClient httpclient = HttpClients.custom().build();
		CloseableHttpResponse response = httpclient.execute(httpget);
		try {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				String str = streamToString(instream, charset);
				return str;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			response.close();
		}
		response.close();

		return "";
	}
	
	public static boolean isBlank(String string) {
		return (isEmpty(string)) || (string.trim().length() == 0);
	}
	private static boolean isEmpty(String string) {
		return (string == null) || (string.equals("null"))
				|| (string.length() == 0);
	}
}
